# -*- coding: utf-8 -*-
import re
import hashlib
import json
import time

from django.core.mail import EmailMultiAlternatives

from utils.code_msg import codeMsg

def match_num(para):
    email = re.match('^.+@(\\[?)[a-zA-Z0-9\\-.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$', para)
    phone = re.match('^\d{11}$', para)
    if email and not phone:
        return {'key': 'email', 'data': email.string}
    elif phone and not email:
        return {'key': 'phone', 'data': phone.string}
    else:
        return None


def send_html_email(request, subject, text_content, from_email, to, link):
    # subject, from_email, to = '注册验证', 'pfadai@163.com', email
    html_content = '<a href="http://' + request.META['SERVER_NAME'] + ':' + request.META['SERVER_PORT'] + link + '">http://' + request.META['SERVER_NAME'] + ':' + request.META['SERVER_PORT'] + link + '</a>'
    # html_content = '<a href="{% url 'username_verify' email %}">{% url 'username_verify' email %}</a>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()


def isPostRight(request):
    uid = request.session.get('user_id')
    user_id = request.POST.get('uid')
    if uid is None:
        return {'status': 'error', 'msg': 'not_login'}
    elif int(uid) != int(user_id):
        return {'status': 'error', 'msg': 'wrong_username'}
    else:
        return True


def getHashNum(request, para):
    cilentIp = request.META.get('REMOTE_ADDR', None)
    clientTime = time.time()
    return hashlib.md5(para + str(int(clientTime)) + str(cilentIp)).hexdigest()


def get_form_errors(form_error):
    if isinstance(form_error, str):
        return form_error
    error_json = form_error.as_json()
    error_json = json.loads(error_json)
    errors = {}
    for error in error_json:
        code = error_json[error][0]['code']
        errors[error] = codeMsg[code]['message']
    return errors


def getTimeObject(timeString):
    pass
    return 0
